import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/finished_in_scan_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/finish_in.dart';
import 'package:flutter_admin/models/odoo/stock_move_line.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input_num.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/utils/http_util.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/utils/eventbus.dart';

class HWProductRegister extends StatefulWidget {
  HWProductRegister({Key? key}) : super(key: key);

  @override
  _HWProductRegisterState createState() => _HWProductRegisterState();
}

class _HWProductRegisterState extends State<HWProductRegister> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  StockQuant stockQuant = StockQuant();
  List<SelectOptionVO> huaweiTemplateList = [];
  var _subscription;
  @override
  void initState() {
    super.initState();
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "HWProductRegister")
        .listen(_onEnvent);
    _loadSelectVO();
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  //处理扫码获得的code
  void _onEnvent(dynamic obj) async{
    try {
      formKey.currentState!.save();
      var scan = obj["scan"].toString();
      obj = obj["scan"];
      // 合单
      List objList = scan.split("|");
      List orderList = objList[0].split(";");
      if(orderList.length != 1){
        CryUtils.message("系统暂不支持合单，请联系管理员");
        return ;
      }
      var barcode = orderList[0];
      var res = await HttpUtil.get(
          "http://10.1.13.100/mesapi/ztkd/Plan/GetPlanInfo?PlanId=$barcode");
      if (!res.success! || res.data.length == 0) {
        CryUtils.message("$barcode生产单号不存在！");
        return;
      }
      var data = res.data[0];
      stockQuant.productorderno = barcode;
      stockQuant.saleorder = data['ContractNo'];
      stockQuant.productCode = data['ProductSpec'];
      stockQuant.productName = data['ProductName'];
      stockQuant.productDes = data['ProductStyle'];
      stockQuant.productUomName = data['UnitName'];
      var res1 = await StockQuantOdooApi.HWRequest("product_check",stockQuant.productCode);
      if(res1.success!){
        stockQuant.productId = res1.data['product_id'].toString();
      }
      setState(() {});
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  _loadSelectVO() async {
    huaweiTemplateList = await DynamicDataApi.getModelSelect(
      model: 'huawei.print_templates',
      name: 'name',
      active: false
    );
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            label: '销售单号',
            enable: false,
            value: stockQuant.saleorder,
          ),
          CryInput(
            label: '生产单号',
            enable: false,
            value: stockQuant.productorderno,
          ),
          CryInput(
            label: '产品名称',
            enable: false,
            value: stockQuant.productName,
          ),
          CryInput(
            label: '产品编码',
            enable: false,
            value: stockQuant.productCode,
          ),
          CryInput(
            label: '规格型号',
            enable: false,
            value: stockQuant.productDes,
          ),
          CryInputNum(
            label: '数量',
            value: stockQuant.quantity,
            onSaved: (v) {
              stockQuant.quantity = v;
            },
            validator: (v) {
              return v!.isEmpty ? "请输入数量" :num.parse(v) ==0? "数量不可以为0": null;
            },
          ),
          CryInput(
            label: '单位',
            enable: false,
            value: stockQuant.productUomName,
          ),
          CryInput(
            label: '备注',
            value: stockQuant.remark,
            onSaved: (v) {
              stockQuant.remark = v;
            },
          ),
          CrySelect(
            label: '打印模板',
            dataList: huaweiTemplateList,
            value: stockQuant.huaweiTemplateId,
            onSaved: (v) {
              stockQuant.huaweiTemplateId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
        ],
      ),
    );

    var footerBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: "确定",
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            // stockQuant.isPackaging = '0';
            // stockQuant.isWeigh = '0';
            stockQuant.exteriorPrintStatus = '0';
            stockQuant.internalPrintStatus = '0';
            StockQuantOdooApi.HWSave(stockQuant.toHWOdooMap()).then((ResponseBodyApi res) {
              if (!res.success!) {
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        title: Text("产品下线登记"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: footerBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
  }


// _loadData() async {
//   print(finishedInScan.productorderno);
//   var finishedInScanToOdoo = [
//     if (finishedInScan.productorderno != null &&
//         finishedInScan.productorderno != '')
//       ['name', '=', finishedInScan.productorderno],
//     if (finishedInScan.productCode != null &&
//         finishedInScan.productCode != '')
//       [
//         'product_id.product_tmpl_id.default_code',
//         '=',
//         finishedInScan.productCode
//       ],
//   ];
//   ResponseBodyApi responseBodyApi = await FinishedInScanOdooApi.page(
//       data: {"domainList": finishedInScanToOdoo});
//   if (responseBodyApi.success!) {
//     tableList = responseBodyApi.data;
//     setState(() {});
//   }
// }

}
